﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using GalaSoft.MvvmLight.Messaging;
using MODEL;
using Common;
using DAL;
using System.IO;
using GalaSoft.MvvmLight;
using System.Windows.Input;
using GalaSoft.MvvmLight.Command;
using System.ComponentModel;
using Common;
using Microsoft.Practices.ServiceLocation;
using GalaSoft.MvvmLight.Views;
using System.Drawing;
using System.IO;

namespace Service
{
    public class PictureInfoService : IPictureInfoService
    {
        public async Task<IEnumerable<AreaWeatherPicture>> QueryAreaWeatherPictures(int? townId)
        {
            return await AreaWeatherPictureDAL.QueryAreaWeatherPictures(townId);
        }

        public async Task<int> UploadWeatherPicture(AreaWeatherPicture areaWeatherPicture, string filePath)
        {
            if (!string.IsNullOrWhiteSpace(filePath) && !filePath.StartsWith("http", StringComparison.OrdinalIgnoreCase))
            {
                if (!File.Exists(filePath))
                {
                    throw new Exception("找不到上传的文件");
                }
                FileInfo fileInfo = new FileInfo(filePath);

                if (fileInfo.Length > 1024 * 1024)
                {
                    throw new Exception("图片太大，请选择小于1Mb的图片");
                }

                string serverFileName = Guid.NewGuid().ToString() + fileInfo.Extension;
                string url = AppSetting.Instance.UploadWeatherPictureFTPUrl.SafeUrlEnd() + serverFileName;

                FtpClient.UploadFile(fileInfo, AppSetting.Instance.UploadWeatherPictureFTPAccount, AppSetting.Instance.UploadWeatherPictureFTPPassword, url);

                areaWeatherPicture.PictureURL = serverFileName;
            }
            else
            {
                areaWeatherPicture.PictureURL = filePath.Replace(AppSetting.Instance.GetWeatherPictureHttpUrl.SafeUrlEnd(),"");
            }
            return await AreaWeatherPictureDAL.InsertAreaWeatherPicture(areaWeatherPicture);
        }

        public async Task<int> DeleteAreaWeatherPicture(List<int> weatherIds)
        {
            return await AreaWeatherPictureDAL.DeleteAreaWeatherPicture(weatherIds);
        }    
    }
}
